package com.yaodian100.mall.member.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.mall.member.util.UserData;

/**
 * 
 * @author apple.chang
 * 
 */
public class SimulateMemberAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7357209477584504298L;

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private MemberService memberService;
	private Member member;
	private String loginID;
	private String loginresult;

	public String simulateLogin() {
		member = memberService.getMemberByLoginId(loginID);
		if (null != member) {
			if (null == member.getActiveDate() && (!"nonmember".equalsIgnoreCase(member.getApplySource()))) {
				loginresult = "unActivate"; // 帐号未激活
				return "toSimulateLogin";
			}

			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			UserData userData = new UserData(request, response);
			userData.killAll();
			userData.setLoginId(member.getLoginId());
			userData.setMemberId(member.getMemberId());

			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			logger.debug("Simulate login cookie == " + new Date().toString() + "  host():" + host + ", apply source{}:"
					+ userData.getApplySource() + ", loginId{}:" + member.getLoginId());
			return "loginOK";
		}
		loginresult = "unfind"; // 帐号不存在
		return "toSimulateLogin";
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	/**
	 * switch to SimulateLogin page
	 * 
	 * @return
	 * @throws Exception
	 */
	public String toSimulateLogin() {
		return "toSimulateLogin";
	}

	public String getLoginresult() {
		return loginresult;
	}

	public String getLoginID() {
		return loginID;
	}

	public void setLoginID(String loginID) {
		this.loginID = loginID;
	}

}